package com.bwie.filter;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

@Component
public class MyFilter implements GatewayFilter {

    @Autowired
    StringRedisTemplate redisTemplate;

    /**
     * 网关过滤器
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取请求参数
        ServerHttpRequest request = exchange.getRequest();
        // 获取响应参数
        ServerHttpResponse response = exchange.getResponse();
        // 获取地址url
        String url = request.getURI().getPath();
        // 获取白名单
        if (url.contains("userLogin")) {
            // 打印信息
            System.out.println("白名单：" + url);
            // 放行
            return chain.filter(exchange);
        }
        // 获取头部token
        String token = request.getHeaders().getFirst("token");
        // 判断是否存在
        if (token == null) {
            // 打印信息
            System.out.println("头部token为空：" + url);
            // 获取状态码
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            // 拦截
            return response.setComplete();
        }
        // 使用jwts解析用户登录的信息
        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        // 获取解析后用户ID
        Integer userId = body.get("userId", Integer.class);
        // 生成key值
        String key = "token:" + userId;
        // 获取redis中的值
        String redisToken = redisTemplate.opsForValue().get(key);
        // 判断是否为空
        if (redisToken == null) {
            // 打印信息
            System.out.println("redisToken为空：" + url);
            // 获取状态码
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            // 拦截
            return response.setComplete();
        }
        // 判断是否和头部token相等
        if (!redisToken.equals(token)) {
            // 打印信息
            System.out.println("token错误：" + url);
            // 获取状态码
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            // 拦截
            return response.setComplete();
        }
        // 判断成功后，为token续期
        redisTemplate.expire(key, 45, TimeUnit.MINUTES);
        // 放行
        return chain.filter(exchange);
    }
}
